class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        result = []
        nRow = len(matrix)
        if nRow==0: return result
        nCol = len(matrix[0])
        up, down, left, right = 0, nRow-1, 0, nCol-1
        while True:
            if up>down or left>right: break
            for c in range(left, right+1):
                result.append(matrix[up][c])
            up+=1
            if up>down or left>right: break
            for r in range(up, down+1):
                result.append(matrix[r][right])
            right-=1
            if up>down or left>right: break
            for c in range(right, left-1, -1):
                result.append(matrix[down][c])
            down-=1
            if up>down or left>right: break
            for r in range(down, up-1, -1):
                result.append(matrix[r][left])
            left+=1
        return result

matrix = [
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

print(Solution().spiralOrder(matrix))